package com.mib.snmp;

import com.mib.browser.DialogException;
import org.snmp4j.*;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;

import java.io.IOException;
import java.util.*;

public class Snmp4jUtil {

    public static List<VariableBinding> snmpGet(Snmp snmp, Target target, String oid) throws IOException {
        List<VariableBinding> resultList = new ArrayList<>();
        PDU pdu = createGetPdu(target, null);
        pdu.add(new VariableBinding(new OID(oid)));

        ResponseEvent responseEvent = snmp.send(pdu, target);
        PDU response = responseEvent.getResponse();

        if (response == null) {
            throw new DialogException("请求数据超时！");
        } else {
            if (response.getErrorStatus() == PDU.noError) {
                Vector<? extends VariableBinding> vbs = response.getVariableBindings();
                resultList.addAll(vbs);
            } else {
                throw new DialogException("请求数据错误:" + response.getErrorStatusText());
            }
        }
        return resultList;
    }

    public static List<VariableBinding> snmpGetNext(Snmp snmp, Target target, String oid) throws IOException {
        List<VariableBinding> resultList = new ArrayList<>();
        PDU pdu = createGetPdu(target, null);
        pdu.add(new VariableBinding(new OID(oid)));

        ResponseEvent responseEvent = snmp.getNext(pdu, target);
        PDU response = responseEvent.getResponse();


        if (response == null) {
            throw new DialogException("请求数据超时！");
        } else {
            if (response.getErrorStatus() == PDU.noError) {
                Vector<? extends VariableBinding> vbs = response.getVariableBindings();
                resultList.addAll(vbs);
            } else {
                throw new DialogException("请求数据错误:" + response.getErrorStatusText());
            }
        }
        return resultList;
    }

    private static PDU createGetPdu(Target target, OctetString contextEngineId) {
        PDU pdu = null;
        if(target.getVersion() == SnmpConstants.version3){
            pdu = new ScopedPDU();
        }else{
            pdu = new PDU();
        }
        pdu.setType(PDU.GET);
        //if not set, will be SNMP engine id
        //pdu.setContextEngineID(contextEngineId);
        //must be same as SNMP agent
        //pdu.setContextName(contextName);
        return pdu;
    }

}
